#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Time    : 2019-10-22 13:53
@Author  : wangb
@Email   : joker_wb@163.com
@File    : date_utils.py
@Software: PyCharm
"""
import datetime
import json
import time
from enum import Enum
import requests
from utils import configloader as cfg
from logger import LOG
API_URL = cfg.get_data_api_url()
# API_URL = "http://timor.tech/api/holiday/info/"
# API_URL = "http://www.baidu.com"




class DateUtils:

    def __init__(self):
        self.next_detect_restday_time = datetime.datetime.now() - datetime.timedelta(seconds=2)
        self.next_detect_workday_time = datetime.datetime.now() - datetime.timedelta(seconds=2)
        self.date_result = None
        self.all_time = cfg.get_time()
        self.status = DataStatus.NORMAL_WORKING  # 初始化状态为正常工作日状态

    def checkssss(self, local_time, redis_utils):
        """
        :param local_time:
        :param redis_utils:
        :return:
        """
        msg = redis_utils.get(cfg.set_time_edit())  # 读一下子时间更新配置。
        if msg is not None:
            msg = json.loads(msg)
            for k, v in msg.items():
                self.all_time[k] = v
            redis_utils.delete(cfg.set_time_edit())  # 删除这个key。
            # 重新进行一次判定
            self.next_detect_restday_time = datetime.datetime.now() - datetime.timedelta(hours=1)
            LOG.info("update time success")

        if local_time > self.next_detect_restday_time:
            self.next_detect_restday_time = datetime.datetime.now() + datetime.timedelta(hours=1)
            """需要做一次是否是节假日的判断"""
            rest_day_results = self.is_rest_day(local_time=local_time)
            self.date_result = rest_day_results.get('result')
            if rest_day_results.get('status'):
                self.status = DataStatus.REST_DAY
            else:
                # 如果请求api出错，也会出现这个情况。默认正常工作日
                self.status = DataStatus.NORMAL_WORKING
        if self.status == DataStatus.NORMAL_WORKING:

            if local_time < self.next_detect_workday_time:
                return self.date_result
            else:

                self.date_result = self.check_worktime(local_time=local_time.timetuple())
                self.next_detect_workday_time = datetime.datetime.now() + datetime.timedelta(seconds=2)
                return self.date_result
        else:
            return self.date_result

    def is_rest_day(self, local_time):
        """
        判断当天是不是休息日
        :param local_time:
        :return:
        """
        LOG.debug('进入判断是不是节假日的函数')
        result = self.check_holiday(local_time=local_time.timetuple())
        # result = {
        #     "code":DataStatus.WORKING
        # }
        if result.get('code') == DataStatus.REST_DAY:
            return {
                "status": True,
                "result": result
            }
        """判断是否是调休"""
        result = self.check_exchange_day_off(local_time=local_time.timetuple())
        if result.get('code') == DataStatus.EXCHANGE_DAY_OFF:
            return {
                "status": True,
                "result": result
            }
        return {
            "status": False,
            "result": result
        }

    def check_holiday(self, local_time):
        """
        检查是否为节假日.  正常工作日对应结果为 0,
                        法定节假日对应结果为 1,
                        节假日调休补班对应的结果为 2，
                        休息日对应结果为 3
        :param today: 今天日子
        :return:是否为节假日
        """

        ymd = time.strftime("%Y%m%d", local_time)
        url = API_URL + str(ymd)
        try:
            result = requests.get(url, timeout=5)
            json_message = json.loads(result.content)
            data = json_message
            if data == 0:
                return {
                    "code": DataStatus.NORMAL_WORKING,
                    "msg": "工作日"
                }
            else:
                return {
                    "code": DataStatus.REST_DAY,
                    "msg": "假日或者节日"
                }
            # if data == 0 or data == 2:
            #     return {
            #         "code": DataStatus.NORMAL_WORKING,
            #         "msg": "正常工作日或者调休"
            #     }
            # if data == 1 or data == 3:
            #     return {
            #         "code": DataStatus.REST_DAY,
            #         "msg": "法定节假日或者休息日"
            #     }

        except Exception as e:
            LOG.error("request holiday api error, the error is {0}", e)
            return {
                'code': DataStatus.ERROR,
                "msg": '请求api出错'
            }

    def check_exchange_day_off(self, local_time):
        """
        判断是不是调休
        :return:
        """
        break_off = self.all_time['break_off']
        """2019-10-22/15:24-2019-10-22/20:24"""
        split_all = break_off.split('-')

        start_all = split_all[0:3]
        end_all = split_all[3:]

        start_year = start_all[0]
        start_month = start_all[1]
        start_day = start_all[2].split('/')[0]
        start_hour = start_all[2].split('/')[1].split(':')[0]
        start_min = start_all[2].split('/')[1].split(':')[1]
        start_time = start_year + start_month + start_day + start_hour + start_min
        end_year = end_all[0]
        end_month = end_all[1]
        end_day = end_all[2].split('/')[0]
        end_hour = end_all[2].split('/')[1].split(':')[0]
        end_min = end_all[2].split('/')[1].split(':')[1]
        end_time = end_year + end_month + end_day + end_hour + end_min

        now_time = time.strftime("%Y%m%d%H%M", local_time)

        if start_time < now_time < end_time:
            return {
                "code": DataStatus.EXCHANGE_DAY_OFF,
                "msg": "调休"
            }

        return {
            "code": DataStatus.NORMAL_WORKING,
            "msg": "正常工作日"
        }

    def check_worktime(self, local_time):
        """
        判断是不是上班时间
        :return:
        """
        now_time = time.strftime("%H:%M", local_time)
        work_time_split = self.all_time['work_time'].split('-')
        noon_sleep_split = self.all_time['noon_sleep'].split('-')
        work_time_morning_start = work_time_split[0]  # 上午上班时间
        work_time_morning_end = noon_sleep_split[0]  # 上午下班时间
        work_time_afternoon_start = noon_sleep_split[1]  # 下午上班时间
        work_time_afternoon_end = work_time_split[1]  # 下午下班时间

        if work_time_morning_start < now_time < work_time_morning_end \
                or work_time_afternoon_start < now_time < work_time_afternoon_end:
            return {
                "code": DataStatus.WORKING,
                "msg": "工作时间"
            }
        return {
            "code": DataStatus.RELEAXING,
            "msg": "休息时间"
        }


class DataStatus(Enum):
    ERROR = -1  # 请求出错
    NORMAL_WORKING = 0  # 正常工作日
    LEGAL_HOLIDAYS = 1  # 法定节假日
    HOLIDAY_OFF = 2  # 节假日调休
    REST_DAY = 3  # 休息日
    EXCHANGE_DAY_OFF = 4  # 调休
    WORKING = 5  # 上班时间
    RELEAXING = 6  # 休息时间


if __name__ == '__main__':
    pass
    print(isinstance(DataStatus.WORKING, int))

    du = DateUtils()
    start = time.time()
    local_time = datetime.datetime.now()
    print(du.check_holiday(local_time.timetuple()))
    # while 1:
    #     local_time = datetime.datetime.now()
    #     if time.time() - start > 3:
    #         # print(du.checkssss(local_time=local_time))
    #         start = time.time()
    #         print(du.check_exchange_day_off(local_time.timetuple()))
